<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>23-四元数解析物体旋转</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      html,
      body {
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
    </style>
  </head>

  <body>
    <script type="module">
      // 引入three.js
      import * as THREE from "three";
      //引入物理引擎cannon
      import * as Cannon from "cannon";
      import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
      import {
        scene,
        camera,
        renderer,
        createLight,
      } from "../utils/three-base";

      const endPoint = new THREE.Vector3(0, 0, 0);
      camera.position.set(0, 0, 10);
      camera.lookAt(endPoint);

      const loader = new THREE.TextureLoader(); //是异步的
      const texture = loader.load("../images/2.png");

      const box = new THREE.Mesh(
        new THREE.BoxGeometry(10, 10, 10),
        new THREE.MeshBasicMaterial({
          map: texture, //贴图
        })
      );

      // const quaternion = new THREE.Quaternion() // 不传参默认（0,0,0,1）
      // const angle = (Math.PI / 180) * 30;
      // const halfAngle = angle / 2;
      // const sinAngle = Math.sin(halfAngle);
      // const cosAngle = Math.cos(halfAngle);
      // const quaternion = new THREE.Quaternion(
      //   sinAngle * 1,
      //   sinAngle * 0,
      //   sinAngle * 0,
      //   cosAngle
      // );

      //使用setFromAxisAngle方法
      // const angle = (Math.PI / 180) * 30;
      // const quaternion = new THREE.Quaternion();
      // const axis = new THREE.Vector3(1, 0, 0);
      // quaternion.setFromAxisAngle(axis, angle);

      // 使用欧拉角setFromEuler方法
      const angle = (Math.PI / 180) * 30;
      const quaternion = new THREE.Quaternion();
      const euler = new THREE.Euler(angle, angle, angle);
      quaternion.setFromEuler(euler);

      box.quaternion.copy(quaternion);

      //控制插件
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.enableDamping = true; //开启惯性,需要和update方法配合使用

      //动画函数
      function animate() {
        requestAnimationFrame(animate);
        controls.update();
        renderer.render(scene, camera);
      }
      animate();
    </script>
  </body>
</html>
